package com.Angaliwa.Whiteboard{
	import com.Angaliwa.Whiteboard;
	import com.Angaliwa.Core;
	
	import flash.display.MovieClip;
	import flash.events.MouseEvent;
	
	import mx.core.UIComponent;
	import mx.effects.Fade;
	import mx.effects.easing.Quartic;
	
	public class Freeform {
		public var enabled:Boolean=false,
			   color:String = "000000",
			   thickness:int = 1,
			   ignoreDistance:int = 5,
			   whiteboard:Whiteboard;
		
		private var layer:UIComponent,
					m:MovieClip,
					steps:Array,
					isDrawing:Boolean=false;
		
		public function init():void{
			this.layer = whiteboard.getLayer();
			layer.cacheAsBitmap=true;
			
			// To avoid the drawing to 'stick' to the mouse when it leaves
			// the whiteboard, we'll finish the drawing when the mouse
			// leaves the whiteboard.
			layer.parent.addEventListener(MouseEvent.MOUSE_DOWN, startDraw);
			layer.parent.addEventListener(MouseEvent.MOUSE_UP, endDraw);
			layer.parent.addEventListener(MouseEvent.MOUSE_MOVE, drawing);
			layer.parent.addEventListener(MouseEvent.ROLL_OUT, endDraw);
		}
		
		public function startDraw(e:MouseEvent):void{
			if(enabled){
				isDrawing=true;
				
				m = new MovieClip();
				layer.addChild(m);
				
				steps = new Array({x:e.localX,y:e.localY});
				
				m.graphics.lineStyle(thickness,uint(color));
				m.graphics.moveTo(e.localX, e.localY);
			}
		}
		
		public function drawing(e:MouseEvent):void{
			if(enabled && isDrawing){
				steps.push({x:e.localX,y:e.localY});
				m.graphics.lineTo(e.localX, e.localY);
			}
		}
		
		public function endDraw(e:MouseEvent):void{
			if(enabled && isDrawing){
				Core.g('growl').message(Core.g('user.user.name')+' drew a line.');
				
				if(whiteboard.settings.get('syncWithServer'))
					whiteboard.features.sync.a(layer.name, {feature:'freeform',
										thickness:thickness,color:color,
										color:color,data:steps,
										user:Core.g('user.user.id').toString()});
			}
			
			isDrawing=false;
		}
		
		public function sync(layerName:String,d:Object):void{
			if(whiteboard.settings.get('syncWithServer')){
				var m:MovieClip = new MovieClip();
				m.graphics.lineStyle(d.thickness,uint(d.color));
				m.graphics.moveTo(d.data[0].x, d.data[0].y);
				
				for(var i:int=1; i < d.data.length; i++){
					m.graphics.lineTo(d.data[i].x, d.data[i].y);
				}
				
				m.alpha=0;
				
				whiteboard.getLayer(layerName).addChild(m);
				
				var ani:Fade = new Fade(m);
				ani.alphaFrom=0;
				ani.alphaTo=1;
				ani.duration=500;
				ani.easingFunction = Quartic.easeIn;
				ani.play();
				
				// DEBUG
				// TODO: Make sure no growl messages are shown at launch.
				// TODO: Add check to see if Growl is enabled.
				if(d.user != Core.g('user.user.id'))
					Core.g('growl').message(Core.g('users').g(d.user).name+' drew a line.');
			}
		}
	}
}